package com.zkca.xf.ui.activity.technicalprotect;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.MyApplication;
import com.zkca.xf.R;
import com.zkca.xf.base.BaseTitleActivity;
import com.zkca.xf.model.javabean.FireControlBean;
import com.zkca.xf.model.javabean.uploadbean.RequestPage;
import com.zkca.xf.presenter.FireControl_LPresenter;
import com.zkca.xf.ui.activity.baidumap.DrivingRouteOverlayAct;
import com.zkca.xf.ui.adapter.RecycRadioAdapter;
import com.zkca.xf.ui.adapter.SingleAdapter;
import com.zkca.xf.ui.adapter.ViewHolder;
import com.zkca.xf.utils.DisplayUtil;
import com.zkca.xf.utils.LogUtil;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.utils.SpaceItemDecoration;
import com.zkca.xf.utils.TimeUtils;
import com.zkca.xf.utils.ToastUtils;
import com.zkca.xf.view.FireAlarmLView;
import com.zkca.xf.view.OnRgitemChangeListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;

public class FSU_LActivity extends BaseTitleActivity implements FireAlarmLView, View.OnClickListener, OnDateSetListener {

    @BindView(R.id.xrv_erc)
    XRecyclerView xrv_erc;
    @BindView(R.id.wushuju)
    ImageView wushuju;
    @BindView(R.id.xre_dtype)
    XRecyclerView xreDtype;
    @BindView(R.id.shaixuan_begantime)
    TextView shaixuanBegantime;
    @BindView(R.id.shaixuanbeganImage)
    ImageView shaixuanbeganImage;
    @BindView(R.id.bgtime)
    RelativeLayout bgtime;
    @BindView(R.id.shaixuan_overtime)
    TextView shaixuanOvertime;
    @BindView(R.id.shaixuan_overimage)
    ImageView shaixuanOverimage;
    @BindView(R.id.ovtime)
    RelativeLayout ovtime;
    @BindView(R.id.shaixuan_cancel)
    TextView shaixuanCancel;
    @BindView(R.id.shaixuan_sure)
    TextView shaixuanSure;
    @BindView(R.id.drawerLayout)
    DrawerLayout drawerLayout;

    private FireControl_LPresenter fireControl_lPresenter;
    private RequestPage requestPage;
    int pageNum = 1;
    int pageSize = 10;
    private int status = 2;
    private SingleAdapter<FireControlBean.DataBean> adapter;
    private LinearLayoutManager linearLayoutManager;
    private List<FireControlBean.DataBean> dataList;
    private ImageView imgRight;
    View pop_selection_state;
    private String[] permissions = {Manifest.permission.CALL_PHONE};
    private String[] permissions2 = {Manifest.permission.ACCESS_COARSE_LOCATION};
    private TextView tv_pop_1, tv_pop_2, tv_pop_3, tv_pop_4, tv_pop_5, tv_pop_6, tv_pop_7;
    TimePickerDialog mDialogHourMinute;
    private String BcreateTime, EcreateTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_electricity_z);
        ButterKnife.bind(this);
        fireControl_lPresenter = new FireControl_LPresenter(this, this);

        initMyview();
        initDrawerLData();
        initResdata(pageNum, status);
    }

    private void initMyview() {
        setTitleText("FSU动环监控");

        setleftImgVisibility(true);

        setImgVisibility(true);
        imgRight = getImgRight();
        imgRight.setOnClickListener(this);
        dataList = new ArrayList<>();


        pop_selection_state = LayoutInflater.from(this).inflate(R.layout.pop_selection_state, null, false);
        tv_pop_1 = pop_selection_state.findViewById(R.id.tv_pop_1);
        tv_pop_2 = pop_selection_state.findViewById(R.id.tv_pop_2);
        tv_pop_3 = pop_selection_state.findViewById(R.id.tv_pop_3);
        tv_pop_4 = pop_selection_state.findViewById(R.id.tv_pop_4);
        tv_pop_5 = pop_selection_state.findViewById(R.id.tv_pop_5);
        tv_pop_6 = pop_selection_state.findViewById(R.id.tv_pop_6);
        tv_pop_7 = pop_selection_state.findViewById(R.id.tv_pop_7);
        tv_pop_1.setOnClickListener(this);
        tv_pop_2.setOnClickListener(this);
        tv_pop_3.setOnClickListener(this);
        tv_pop_4.setOnClickListener(this);
        tv_pop_5.setOnClickListener(this);
        tv_pop_6.setOnClickListener(this);
        tv_pop_7.setOnClickListener(this);

        linearLayoutManager = new LinearLayoutManager(mContext);
        xrv_erc.setLayoutManager(linearLayoutManager);
        xrv_erc.addItemDecoration(new SpaceItemDecoration(DisplayUtil.dip2px(
                mContext, 0.5f)));
        xrv_erc.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                xrv_erc.setLoadingMoreEnabled(true);
                dataList.clear();
                pageNum = 1;
                initResdata(pageNum, status);
            }

            @Override
            public void onLoadMore() {
                pageNum++;
                initResdata(pageNum, status);
            }
        });

        adapter = new SingleAdapter<FireControlBean.DataBean>(mContext, dataList, R.layout.common_list) {
            @Override
            public void convert(ViewHolder holder, final FireControlBean.DataBean dataBean, int position) {

                TextView unitName = holder.getView(R.id.unitName);
                String unitName1 = dataBean.getUnitName();
                unitName.setText(unitName1);//单位名称

                TextView devid = holder.getView(R.id.devid);
                String devId = dataBean.getChuanhao();
                devid.setText("" + devId);

                TextView alarmTime = holder.getView(R.id.alarmtime);
                final long alarmTime1 = dataBean.getCreateTime();
                alarmTime.setText("" + TimeUtils.getFormatDate2(alarmTime1));

                TextView installposition = holder.getView(R.id.installposition);
                String installPosition = dataBean.getDizhi();
                installposition.setText("" + installPosition);

                TextView unitaddress = holder.getView(R.id.unitaddress);
                String unitAddress = dataBean.getUnitAddress();
                unitaddress.setText("" + unitAddress);

                TextView contact = holder.getView(R.id.contact);
                String contact1 = dataBean.getContact();
                contact.setText("" + contact1);

                TextView telPhone = holder.getView(R.id.telphone);
                final String telphone = dataBean.getTelephone();
                telPhone.setText("" + telphone);

                TextView comment = holder.getView(R.id.comment);
                comment.setText(dataBean.getComment());

                TextView bujian = holder.getView(R.id.bujian);
                RelativeLayout bujian_r = holder.getView(R.id.bujian_r);
//                int msgType = dataBean.getMsgType();
//                if (2==msgType){
//                    bujian_r.setVisibility(View.VISIBLE);
//                    bujian.setText("部件名称："+dataBean.getFtyName()+"  回路号："+dataBean.getLoopId()+"  地址号："+dataBean.getAddrId());
//                }else {
                bujian_r.setVisibility(View.GONE);
//                }


                TextView devstatus = holder.getView(R.id.devstatus);
                if (dataBean.getStatus() == 0) {
                    devstatus.setText("正常");
                    devstatus.setTextColor(Color.rgb(51, 51, 51));
                } else if (dataBean.getStatus() == 1) {
                    devstatus.setText("预警");
                    devstatus.setTextColor(Color.rgb(216, 29, 29));
                } else if (dataBean.getStatus() == 2) {
                    devstatus.setText("报警");
                    devstatus.setTextColor(Color.rgb(216, 29, 29));
                } else if (dataBean.getStatus() == 3) {
                    devstatus.setText("断线");
                    devstatus.setTextColor(Color.rgb(216, 29, 29));
                } else if (dataBean.getStatus() == 4) {
                    devstatus.setText("异常");
                    devstatus.setTextColor(Color.rgb(216, 29, 29));
                } else if (dataBean.getStatus() == 5) {
                    devstatus.setText("故障");
                    devstatus.setTextColor(Color.rgb(216, 29, 29));
                }
                final double longitude = dataBean.getJingdu();
                final double latitude = dataBean.getWeidu();
                holder.getView(R.id.iv_lujing).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        final Intent intent = new Intent(mContext, DrivingRouteOverlayAct.class);
                        intent.putExtra("jingdu", longitude);
                        intent.putExtra("weidu", latitude);
                        if (longitude==0.0||latitude==0.0){
                            ToastUtils.show(mContext,"目标点经纬度信息不完善，无法进行线路规划");
                            return;
                        }
                        RxPermissions rxPermissions = new RxPermissions(FSU_LActivity.this);
                        rxPermissions.request(permissions2)
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(@NonNull Boolean granted) throws Exception {
                                        //同意授权
                                        if (granted) {
                                            if (ActivityCompat.checkSelfPermission(FSU_LActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                                ToastUtils.show(FSU_LActivity.this, "请添加定位权限");
                                                return;
                                            }
                                            startActivity(intent);
                                        } else {//拒绝
                                            ToastUtils.show(FSU_LActivity.this, "请添加定位权限");
                                        }
                                    }
                                });
                    }
                });


                holder.getView(R.id.iv_tel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        final Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telphone));

                        RxPermissions rxPermissions = new RxPermissions(FSU_LActivity.this);
                        rxPermissions.request(permissions)
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(@NonNull Boolean granted) throws Exception {
                                        //同意授权
                                        if (granted) {
                                            if (ActivityCompat.checkSelfPermission(FSU_LActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                                ToastUtils.show(FSU_LActivity.this, "请添加手机拨打电话权限");
                                                return;
                                            }
                                            startActivity(intent);
                                        } else {//拒绝
                                            ToastUtils.show(FSU_LActivity.this, "请添加手机拨打电话权限");
                                        }
                                    }
                                });

                    }
                });
                holder.setItemViewOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(FSU_LActivity.this, FSU_XActivity.class);
                        intent.putExtra("shuanbean", dataBean);
                        startActivity(intent);
                    }
                });

            }
        };
        xrv_erc.setAdapter(adapter);

    }

    private void initDrawerLData() {

        final ArrayList<String> secondList = new ArrayList<>();
        secondList.add("正常数据");
        secondList.add("预警数据");
        secondList.add("报警数据");
        secondList.add("断线数据");
        secondList.add("异常数据");
        secondList.add("故障数据");
        secondList.add("全部数据");

        final ArrayList<Integer> secondListNo = new ArrayList<>();
        secondListNo.add(0);
        secondListNo.add(1);
        secondListNo.add(2);
        secondListNo.add(3);
        secondListNo.add(4);
        secondListNo.add(5);
        secondListNo.add(-1);
        final RecycRadioAdapter recycRadioAdapter = new RecycRadioAdapter(mContext, secondList);
        xreDtype.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false));
        recycRadioAdapter.setOnRgitemChangeListenner(new OnRgitemChangeListener() {
            @Override
            public void onItemCheckChange(int i) {
                String s = secondList.get(i);
                if (xreDtype.getScrollState() != RecyclerView.SCROLL_STATE_IDLE || (xreDtype.isComputingLayout() == false)) {
                    recycRadioAdapter.notifyDataSetChanged();
                    status = secondListNo.get(i);
                }
            }
        });
        xreDtype.setAdapter(recycRadioAdapter);

        mDialogHourMinute = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId("选择时间")
                .setMinMillseconds(System.currentTimeMillis() - 573050000000L)
                .setMaxMillseconds(System.currentTimeMillis())
                .setCallBack(this)
                .build();

        bgtime.setOnClickListener(this);
        ovtime.setOnClickListener(this);
        shaixuanCancel.setOnClickListener(this);
        shaixuanSure.setOnClickListener(this);
        EcreateTime = TimeUtils.getTimeL();
        long time = System.currentTimeMillis();//获取系统时间的10位的时间戳
        long days7 = 7 * 24 * 3600 * 1000;
        long etime = time - days7;
        BcreateTime = TimeUtils.getFormatDateYMD(etime);
        LogUtil.e("时间：", BcreateTime + "<><><>" + EcreateTime);
    }

    private void initResdata(int pagenum, int status) {
        Map map = new HashMap<String, Object>();
        map.put("BcreateTime", BcreateTime);
        map.put("EcreateTime", EcreateTime);
        if (status != -1) {
            map.put("status", status+"");
        }
        requestPage = new RequestPage();
        requestPage.setAccessId(SPUtil.getString(this, Constants_SP.ACCESSID));
        requestPage.setPageNum(pagenum);
        requestPage.setPageSize(pageSize);
        requestPage.setParam(map);
        requestPage.setTimeStamp(TimeUtils.getTime());
        requestPage.setSign(MyApplication.getInstance().generateSign(requestPage));
        fireControl_lPresenter.getShuan(requestPage);
    }

    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void showError(String msg) {

        wushuju.setVisibility(View.VISIBLE);
        ToastUtils.show(this, msg);

    }

    @Override
    public void getFireAlarm(String s) {
        LogUtil.e("121", s);
        Gson gson = new Gson();
        FireControlBean friealarmLbean = gson.fromJson(s, FireControlBean.class);
        try {
            xrv_erc.refreshComplete();
            xrv_erc.loadMoreComplete();
            if (friealarmLbean.getResult() == 0) {
                List<FireControlBean.DataBean> data = friealarmLbean.getData();
                if (data != null && data.size() > 0) {
                    dataList.addAll(data);
                }
                if (friealarmLbean.getTotalpage() == pageNum) {
                    xrv_erc.setLoadingMoreEnabled(false);
                }else {
                    xrv_erc.setLoadingMoreEnabled(true);
                }
                if (pageNum == 1 && data.size() == 0) {
                    wushuju.setVisibility(View.VISIBLE);
                } else {
                    wushuju.setVisibility(View.GONE);
                }
                adapter.notifyDataSetChanged();
            } else {
                wushuju.setVisibility(View.VISIBLE);
                ToastUtils.show(this, friealarmLbean.getInfo());
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.im_base_right:
                //PopWindowUtil.SelectionState(ElectricityZ_LActivity.this, pop_selection_state, imgRight);
                if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                    drawerLayout.closeDrawer(Gravity.RIGHT);
                } else {
                    drawerLayout.openDrawer(Gravity.RIGHT);
                }
                break;
            case R.id.bgtime:
                mDialogHourMinute.show(getSupportFragmentManager(), "btime");
                break;
            case R.id.ovtime:
                mDialogHourMinute.show(getSupportFragmentManager(), "etime");
                break;
            case R.id.shaixuan_cancel:
                drawerLayout.closeDrawers();
                break;
            case R.id.shaixuan_sure:
                dataList.clear();
                pageNum = 1;
                initResdata(1, status);
                drawerLayout.closeDrawers();
                break;

        }
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        String tag = timePickerView.getTag();
        switch (tag) {
            case "btime":
                shaixuanBegantime.setText(TimeUtils.getFormatDateYMDhm(millseconds));
                BcreateTime = TimeUtils.getFormatDateYMDhm(millseconds);
                break;
            case "etime":
                shaixuanOvertime.setText(TimeUtils.getFormatDateYMDhm(millseconds));
                EcreateTime = TimeUtils.getFormatDateYMDhm(millseconds);
                break;
        }
    }
}